package com.atguigu.tree;

/**
 * description:
 * Created by 才睡醒 on 2021-07-18
 */
public class ArrBinaryTreeDemo {
    public static void main(String[] args) {
        int[] arry = {1, 2, 3, 4, 5, 6, 7};
        ArrBinarytree arrBinarytree = new ArrBinarytree(arry);
        System.out.println("前序遍历");
        arrBinarytree.preOrder();
        System.out.println();
        System.out.println("后序遍历");
        arrBinarytree.postOrder(0);
    }
}
//编写一个arrBinarytree，实现顺序存储二叉树的遍历

class ArrBinarytree {
    private int[] arr;

    public ArrBinarytree(int[] arr) {
        this.arr = arr;
    }

    //编写一个方法，完成顺序存储二叉树的前序遍历
    public void preOrder(int index) {
        //如果数组为空，或者arr.length=0
        if (arr == null || arr.length == 0) {
            System.out.println("数组为空，不能按照二叉树前序遍历");
        }
        System.out.print(arr[index]);
        //向左递归遍历
        if ((index * 2 + 1) < arr.length - 1) {

            preOrder(2 * index + 1);
        }
        //向右递归遍历
        if ((index * 2 + 2) < arr.length) {
            preOrder(2 * index + 2);
        }
    }

    public void preOrder() {
        preOrder(0);
    }

    public void postOrder(int index) {
        if (arr == null || arr.length == 0) {
            System.out.println("数组为空");
        }
        if ((index * 2 + 1) < arr.length) {
            postOrder(index * 2 + 1);
        }
        if ((index * 2 + 2) < arr.length) {
            postOrder(index * 2 + 2);
        }
        System.out.print(arr[index]);
    }
}
